let _$ = (function () {
    // 创建xhr
    let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    if (!xhr) {
        throw new Error("浏览器起不支持http请求");
    }
    // 处理参数
    function _doAjax(opt) {
        let params = opt || {},
            type = (opt.type || "GET").toUpperCase(),
            url = opt.url,
            async = opt.async || true,
            data = opt.data || null,
            error = opt.error || function () { },
            success = opt.success || function () { },
            complete = opt.complete || function () { };

        if (!url) {
            throw new Error("请填写URL");
        }
        // 请求
        xhr.open(type, url, async);
        type === "POST" && xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(type === "GET" ? null : formatData(data));
        // 响应
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                success(JSON.parse(xhr.responseText));
            }
            if (xhr.status === 404) {
                error();
            }
            complete();
        }
    }
    function formatData(data) {
        let str = "";
        for (const key in data) {
            str += key + "=" + data[key] + "&"
        }
        return str.replace(/&$/, "");
    }
    return {
        ajax: function (opt) {
            _doAjax(opt);
        },
        post: function (url, data, callback) {
            _doAjax({
                type: "POST",
                url: url,
                data: data,
                success: callback
            })
        },
        get: function (url, callback) {
            _doAjax({
                type: 'GET',
                url: url,
                success: callback
            })
        }
    }
})();